//创建store
import {defineStore} from "pinia";
import {Menu} from "@/interface/menu";
import {LoadMenuTree} from "@/utils/menu";
import {UserMenuListR} from "@/api/user";

const useMenuStore = defineStore('menu', {
  //定义状态：一个函数，返回一个对象
  state: () => {
    return {
      list: <Menu[]>[], //菜单列表
      buttons: <Menu[]>[],//按钮列表
      permsTree: <Menu[]>[],//权限树
      // perms: <string[]>[]
    }
  },

  //定义getters，等同于组件的计算属性
  getters: {
    //getter 函数接收 state 作为参数，推荐使用箭头函数
    // list: state => state.list
  },

  //定义actions，有同步和异步两种类型
  actions: {
    //异步 action，一般用来处理异步逻辑
    async get() {
      await UserMenuListR().then(res => res.data).then(res => {
        switch (res.code) {
          case 200:
            let menus = JSON.parse(JSON.stringify(res.data)) as Menu[]
            let parents = menus.filter((m) => m.parent_id === 0 && m.type===1)
            let children = menus.filter((m) => m.parent_id !== 0 && m.type===1)

            LoadMenuTree(parents, children)
            //菜单列表
            this.list = parents
            //按钮列表
            this.buttons = menus.filter((m) => m.type === 2)

            //权限树
            let perms = JSON.parse(JSON.stringify(res.data)) as Menu[]
            let permsParents = perms.filter((m) => m.parent_id === 0)
            let permsChildren = perms.filter((m) => m.parent_id !== 0)
            LoadMenuTree(permsParents, permsChildren)
            this.permsTree = permsParents

            break
          default:
            console.log('请求菜单列表失败:', res.msg)
        }
      })
    },
    flush(){
      this.list = []
      this.buttons = []
      this.permsTree = []
    }
  }
})

export default useMenuStore